//
//  STCommodityDetailController.swift
//  iPhone
//
//  Created by Toj on 8/9/22.
//

import UIKit

enum CommoditySegmentType: String {
    case mobile = "MOBILE VIP"
    case tv     = "TV VIP"
    case all    = "ALL"
}

private let buyButtonHeight: CGFloat = 130

class STCommodityDetailController: STBaseViewController {
    
    public var utmString = ""
    
    public var toSegmentType: CommoditySegmentType = .mobile
    private var selectedSegmentType: CommoditySegmentType = .mobile { willSet {
        guard vcs.count > 0 else { return }
        
        let oldTypeString = selectedSegmentType.rawValue
        let oldVC = vcs[oldTypeString]
        oldVC?.view.isHidden = true
        oldVC?.scrollToTop()
        
        let newTypeString = newValue.rawValue
        guard let newVC = vcs[newTypeString] else { return }
        if newVC.view.superview == nil {
            view.addSubview(newVC.view)
            newVC.view.snp.makeConstraints { make in
                make.left.right.bottom.top.equalTo(view)
            }
        }
        newVC.view.isHidden = false
        newVC.headerView = headerView
        newVC.scrollToTop()
    } }
    
    
    private lazy var goPayView: BuyNowFloatingView = {
        let view = BuyNowFloatingView()
        //view.delegate = self
        return view
    }()
    
    private lazy var headerView: CommodityHeaderView = {
        let view = CommodityHeaderView()
        view.delegate = self
        return view
    }()
    
    private lazy var vcs: [String: STBaseCommodityController] = [:]
    
    private lazy var mobileCommodityVC: STMobileCommodityController = {
        let vc = STMobileCommodityController()
        vc.commodityDelegate = self
        vc.bottomOffset = buyButtonHeight
        vc.type = .mobile
        return vc
    }()
    
    private lazy var tvCommodityVC: STTVCommodityController = {
        let vc = STTVCommodityController()
        vc.commodityDelegate = self
        vc.type = .tv
        return vc
    }()
    
    private lazy var allCommodityVC: STAllCommodityController = {
        let vc = STAllCommodityController()
        vc.commodityDelegate = self
        vc.type = .all
        return vc
    }()
    
    private lazy var rightItem: UIBarButtonItem = {
        let item = UIBarButtonItem(target: self, action: #selector(didTapQuestion), for: .touchUpInside, imageNormal: "commodity_question")
        return item
    }()
    
    private lazy var titleView: STCommoditySegmentView = {
        let view = STCommoditySegmentView()
        view.delegate = self
        view.normalFont = UIFont.boldSystemFont(ofSize: 14)
        view.selectedFont = UIFont.boldSystemFont(ofSize: 14)
        view.isSelectedImageViewHidden = true
        view.segmentBackgroundColor = UIColor(hex: "#171B22")
        return view
    }()
    
    private lazy var titleLabel: UILabel = {
        let view = UILabel()
        view.text = "VIP"
        view.font = UIFont.boldSystemFont(ofSize: 14)
        view.textColor = UIColor(hex: "#E8CD8C")
        return view
    }()
    
    // ["MOBILE VIP"], ["MOBILE VIP", "ALL"], ["MOBILE VIP", "TV VIP", "ALL"]
    var randomTitles: [String] {
        if !utmString.isEmpty {
            return [CommoditySegmentType.mobile.rawValue]
        }
        let tvfunction = arc4random_uniform(2) == 1
        if !tvfunction {
            return [CommoditySegmentType.mobile.rawValue,
                    CommoditySegmentType.all.rawValue]
        }
        
        return [CommoditySegmentType.mobile.rawValue,
                CommoditySegmentType.tv.rawValue,
                CommoditySegmentType.all.rawValue]
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let titles = randomTitles
        headerView.segmentView.titles = titles
        headerView.freeIcon.isHidden = !titles.contains(CommoditySegmentType.tv.rawValue)
        titleView.titles = titles
        headerView.model = nil
        
        navigationItem.rightBarButtonItem = rightItem
        navigationItem.titleView = titleLabel
        
        vcs = [CommoditySegmentType.mobile.rawValue: mobileCommodityVC,
               CommoditySegmentType.tv.rawValue: tvCommodityVC,
               CommoditySegmentType.all.rawValue: allCommodityVC]
        addChild(mobileCommodityVC)
        addChild(tvCommodityVC)
        addChild(allCommodityVC)
        
        // 初始化选中的标签
        selectedSegmentType = toSegmentType
        
        view.addSubview(goPayView)
        setupRelayoutPayView(false, animate: false)
        goPayView.cm_shadow()
    }
    
    private var isShow_ = false
    private func setupRelayoutPayView(_ isShow: Bool = true, animate: Bool = true) {
        
        let y = isShow ? (view.bounds.height - buyButtonHeight) : view.bounds.height
        
        if !animate {
            isShow_ = isShow
            goPayView.frame = CGRect(x: 0, y: CGFloat.sr_height, width: CGFloat.sr_width, height: buyButtonHeight)
            return
        }
        
        if isShow {
            if isShow_ && !goPayView.isHidden { return }
            isShow_ = isShow
            goPayView.isHidden = false
            UIView.animate(withDuration: 0.2) {
                self.goPayView.frame = CGRect(x: 0, y: y, width: CGFloat.sr_width, height: buyButtonHeight)
            }
            return
        }
        
        if !isShow_ { return }
        isShow_ = isShow
        UIView.animate(withDuration: 0.2) {
            self.goPayView.frame = CGRect(x: 0, y: y, width: CGFloat.sr_width, height: buyButtonHeight)
        } completion: { isCompletion in
            self.goPayView.isHidden = true
        }
    }
    
    func didTapSegment(title: String) {
        let type = CommoditySegmentType(rawValue: title) ?? .mobile
        
        selectedSegmentType = type
        headerView.delegate = self
    }
    
    @objc private func didTapQuestion() {
        // print("-->toj: " + #function)
    }
}

extension STCommodityDetailController: CommodityHeaderViewDelegate {
    func commodityHeaderView(_ view: CommodityHeaderView, didTapSegment index: Int, title: String) {
        didTapSegment(title: title)
        titleView.selectedIndex = index
        
        if !view.segmentView.titles.contains(CommoditySegmentType.tv.rawValue)
        { return }
        headerView.freeIcon.isHidden = title == CommoditySegmentType.tv.rawValue
    }
}

extension STCommodityDetailController: STCommoditySegmentViewDelegate {
    func commoditySegmentView(_ view: STCommoditySegmentView, didTapSegment index: Int, title: String) {
        didTapSegment(title: title)
        headerView.segmentView.selectedIndex = index
        
        setupRelayoutPayView(false, animate: false)
        
        if !view.titles.contains(CommoditySegmentType.tv.rawValue) { return }
        headerView.freeIcon.isHidden = title == CommoditySegmentType.tv.rawValue
    }
}

extension STCommodityDetailController: STCommodityControllerDelegate {
    
    func commodityController(_ vc: STBaseCommodityController, scrollView: UIScrollView, headerAlpha: CGFloat) {
        
        if headerAlpha > 0.9 {
            guard navigationItem.rightBarButtonItem != nil else { return }
            var offset: CGFloat = 38
            if titleView.titles.count == 1 {
                offset = 100 // 居中显示
            }
            let width = CGFloat.sr_width - offset
            navigationItem.rightBarButtonItem = nil
            titleView.frame = CGRect(x: 0, y: 0, width: width, height: 44)
            navigationItem.titleView = titleView
            return
        }
        
        guard navigationItem.rightBarButtonItem == nil else { return }
        navigationItem.titleView = titleLabel
        navigationItem.rightBarButtonItem = rightItem
    }
    
    func commodityController(_ vc: STBaseCommodityController, scrollView: UIScrollView, isShow: Bool) {
        
        // print("-->toj: isShow: \(isShow)")
        
        setupRelayoutPayView(isShow)
    }
}
